package java_class_work.week08.internet.sendStringDemo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * @Author Tiam
 * @Date 2022/11/4 21:10
 * @Description:
 */
public class ServerThread implements Runnable {
    private Socket socket;

    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        while (true) {
            send();
        }
    }

    private void send() {
        try {
            BufferedReader in = null;
            PrintWriter out = null;
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            String mes = null;
            try {
                mes = in.readLine();
            } catch (IOException e) {
                System.out.println("客户端异常关闭");
                e.printStackTrace();
                System.exit(-1);
            }
            // 判断是否是否为私发, 截取端口号5位
            String to = null;
            if (mes.length() > 5) {
                to = mes.substring(0, 5);

                // 找到端口目标端口 to, 向其发送消息后停止执行
                for (Socket socket1 : RunServer.map.keySet()) {
                    if (to.equals(String.valueOf(socket1.getPort()))) {
                        out = new PrintWriter(socket1.getOutputStream(), true);
                        out.println(mes.substring(5));
                        return;
                    }
                }
            }


            // 如未找到目标端口, 按群发消息处理, 转发给所有在线的客户端
            String message = "【群发消息】" + socket.getPort() + ":" + mes;
            System.out.println(message);
            // 将某个客户端发送过来的消息, 转发给所有在线用户
            for (Socket socket1 : RunServer.map.keySet()) {
                // 跳过自己
                if (socket1 == this.socket) continue;
                out = new PrintWriter(socket1.getOutputStream(), true);
                out.println(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
